package admin

import (
	"booking/common/handler"
	"booking/common/utils"
	"booking/common/validator"
	"booking/models"
	"strings"

	"github.com/gin-gonic/gin"
)

func Save(c *gin.Context) {
	var params struct {
		Id       uint   `json:"id,omitempty"`
		Username string `json:"username" binding:"required"`
		Nickname string `json:"nickname" binding:"required"`
		Mobile   string `json:"mobile" binding:"required"`
		Password string `json:"password,omitempty"`
	}
	if err := c.ShouldBindJSON(&params); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}

	params.Password = strings.TrimSpace(params.Password)
	if params.Password != "" && len(params.Password) < 6 {
		handler.Error("密码长度必须大于等于6", c)
		return
	}

	var adminModel models.Admin
	if params.Id > 0 {
		models.Db.Model(models.Admin{}).
			Where("id = ?", params.Id).
			First(&adminModel)
		if adminModel.Id <= 0 {
			handler.Error("用户不存在", c)
			return
		}
	}
	var mobileExist, loginNameExist models.Admin
	queryMobile := models.Db.Model(models.Admin{}).
		Where("mobile = ?", params.Mobile, models.IsDelNo)
	queryUsername := models.Db.Model(models.Admin{}).
		Where("username = ?", params.Username)
	if adminModel.Id > 0 {
		queryMobile.Where("id <> ?", adminModel.Id)
		queryUsername.Where("id <> ?", adminModel.Id)
	}
	queryMobile.First(&mobileExist)
	queryUsername.First(&loginNameExist)
	if mobileExist.Id > 0 {
		handler.Error("手机号已存在", c)
		return
	}
	if loginNameExist.Id > 0 {
		handler.Error("账号已存在", c)
		return
	}
	if adminModel.Id <= 0 {
		adminModel.Password = utils.BcryptHash(params.Password)
	}
	adminModel.Username = params.Username
	adminModel.Nickname = params.Nickname
	adminModel.Mobile = params.Mobile
	err := models.Db.Save(&adminModel).Error
	if err != nil {
		handler.Error(err.Error(), c)
		return
	}
	handler.Success(nil, c)
}

func RestPassword(c *gin.Context) {
	var params struct {
		Id uint `json:"id" binding:"required,gt=0"`
	}
	if err := c.ShouldBindJSON(&params); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}
	var userinfo models.Admin
	models.Db.Model(models.Admin{}).
		Where("id = ?", params.Id).First(&userinfo)
	if userinfo.Id <= 0 {
		handler.Error("用户不存在", c)
		return
	}
	userinfo.Password = utils.BcryptHash("admin888")
	if err := models.Db.Save(&userinfo).Error; err != nil {
		handler.Error("重置密码失败", c)
		return
	}
	handler.Success(nil, c)
}
